<!--
 * @Descripttion: (/HostMachine)
 * @version: (1.0)
 * @Author: (admin)
 * @Date: (2024-11-01)
 * @LastEditors: (admin)
 * @LastEditTime: (2024-11-01)
-->
<template>
  <div class="app-container">
    <!-- :model属性用于表单验证使用 比如下面的el-form-item 的 prop属性用于对表单值进行验证操作 -->
    <!-- <el-form :model="queryParams" size="small" label-position="right" inline ref="queryForm" :label-width="labelWidth"
      v-show="showSearch" @submit.native.prevent>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->
    <!-- 工具区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" :disabled="single" plain icon="el-icon-edit" size="mini"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" :disabled="multiple" plain icon="el-icon-delete" size="mini"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" size="mini" :disabled="multiple" icon="el-icon-edit"
          @click="handleSetHost">设置参数</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据区域 -->
    <el-table :data="dataList" v-loading="loading" ref="table" border highlight-current-row @sort-change="sortChange"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <!-- <el-table-column prop="id" label="主键" align="center" :show-overflow-tooltip="true" /> -->
      <el-table-column prop="sort" label="交换机排序" align="center" />
      <el-table-column prop="machineNo" label="交换机编号" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="machineName" label="交换机名称" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="location" label="交换机位置" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="machineSence" label="交换机场景" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="ip" label="IP" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="status" label="交换机连接状态" align="center">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column prop="wStatus" label="喷雾状态" align="center">
        <template slot-scope="scope">
          <dict-tag :options="wStatusOptions" :value="scope.row.wStatus" />
        </template>
      </el-table-column>
      <!-- <el-table-column prop="workMode" label="工作模式" align="center" :show-overflow-tooltip="true" /> -->

      <el-table-column label="操作" align="center" width="240">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleSetHost(scope.row)">设置参数</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination class="mt10" background :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :lock-scroll="false" :visible.sync="open">
      <el-form ref="form" :model="form" :rules="rules" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="12">
            <el-form-item label="主机名称" prop="machineName">
              <el-input v-model="form.machineName" placeholder="请输入主机名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="主机编号" prop="machineNo">
              <el-input v-model="form.machineNo" placeholder="请输入主机编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="交换机场景" prop="machineSence">
              <!-- <el-input v-model="form.machineSence" placeholder="请输入主机场景" /> -->
              <el-select v-model="form.machineSence" placeholder="请选择交换机场景" style="width: 320px;">
                <el-option v-for="item in typeOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交换机位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入交换机位置" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="IP" prop="ip">
              <el-input v-model="form.ip" placeholder="请输入IP" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="交换机连接状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in statusOptions" :key="item.dictValue" :label="item.dictValue">{{ item.dictLabel
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="喷雾状态" prop="wStatus">
              <el-radio-group v-model="form.wStatus">
                <el-radio v-for="item in wStatusOptions" :key="item.dictValue" :label="item.dictValue">{{ item.dictLabel
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工作模式" prop="workMode">
              <el-input v-model="form.workMode" placeholder="请输入工作模式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model.number="form.sort" controls-position="right" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-button type="primary" @click="addDetail">添加主机</el-button>
          </el-col>
        </el-row>
        <el-row v-for="(item, index) in form.details" :key="index">
          <el-col :span="6">
            <el-form-item :label="'名称' + (index + 1)" :prop="'details.' + index + '.id'"
              :rules="[{ required: true, message: '主机名称不能为空', trigger: 'change' }]">
              <!-- <el-input v-model="item.project"></el-input> -->
              <el-select v-model="item.id" placeholder="请选择主机名称" @change="labelClick(index, $event)">
                <el-option v-for="options in Sensoroptions" :key="options.id" :label="options.sensorName"
                  :value="options.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="60px" :label="'编号' + (index + 1)" ww>
              <el-input v-model="item.sensorNo" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="60px" :label="'类型' + (index + 1)">
              <el-input v-model="item.type" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="60px" :label="'地址' + (index + 1)">
              <el-input v-model="item.location" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="'报警值下限' + (index + 1)" :prop="'details.' + index + '.alarmLow'"
              :rules="[{ required: true, message: '报警值下限不能为空', trigger: 'change' }]">
              <el-input v-model="item.alarmLow" width="251px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="'报警值上限' + (index + 1)" :prop="'details.' + index + '.alarmUpper'"
              :rules="[{ required: true, message: '报警值上限不能为空', trigger: 'change' }]">
              <el-input v-model="item.alarmUpper"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button @click="removeDetail(index)">移除</el-button>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog title="设置参数" :lock-scroll="false" :visible.sync="open2">
      <el-form :model="formSet" ref="formSet" :rules="setRules" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="12">
            <el-form-item label="定时喷雾" prop="datePW">
              <el-time-picker v-model="formSet.datePW" value-format="HH:mm" format="HH:mm" placeholder="选择定时喷雾时间">
              </el-time-picker>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否喷雾" prop="isPW">
              <el-switch v-model="formSet.isPW" active-color="#13ce66" inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancelSet">取 消</el-button>
        <el-button type="primary" @click="submitSetForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listHostMachine,
  addHostMachine,
  delHostMachine,
  updateHostMachine,
  getHostMachine,
  getSensorList,
  updateSetHostMachine
} from '@/api/dust/hostMachine.js';

export default {
  name: "hostmachine",
  data() {
    return {
      labelWidth: "100px",
      formLabelWidth: "130px",
      // 选中id数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sort: undefined,
        sortType: undefined,
      },
      // 弹出层标题
      title: "",
      // 操作类型 1、add 2、edit
      opertype: 0,
      // 是否显示弹出层
      open: false,
      open2: false,
      // 表单参数
      form: {
        details: [{ id: '', sensorName: '', sensorNo: '', type: '', location: "", alarmUpper: "", alarmLow: "" }]
      },
      formSet: {
        ids: "",
        datePW: "",
        isPW: true
      },
      typeOptions: [],
      Sensoroptions: [],
      // 主机连接状态选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
      statusOptions: [{ dictLabel: '正常', dictValue: '0' }, { dictLabel: '关闭', dictValue: '1' }],
      // 水阀状态选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
      wStatusOptions: [{ dictLabel: '正常', dictValue: '0' }, { dictLabel: '关闭', dictValue: '1' }],
      // 数据列表
      dataList: [],
      // 总记录数
      total: 0,
      // 提交按钮是否显示
      btnSubmitVisible: true,
      // 表单校验
      rules: {
        machineName: [
          { required: true, message: "主机名称不能为空", trigger: "blur" }
        ],
        machineNo: [
          { required: true, message: "主机编号不能为空", trigger: "blur" }
        ],
        machineSence: [
          { required: true, message: "主机场景不能为空", trigger: "blur" }
        ],
        location: [
          { required: true, message: "主机位置不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        ip: [
          { required: true, message: "主机IP不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "主机连接状态不能为空", trigger: "blur" }
        ],
        wStatus: [
          { required: true, message: "水阀状态不能为空", trigger: "blur" }
        ]


      },
      setRules: {
        datePW: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        isPW: [
          { required: true, message: "定时喷雾时间不能为空", trigger: "blur" }
        ]
      },
    };
  },
  created() {
    // 列表数据查询
    this.getList();
    this.getSensoroptions();
    this.getDicts('host_scene').then((response) => {
      this.typeOptions = response.data
    })
  },
  methods: {

    labelClick(index, event) {
      let choosenItem = this.Sensoroptions.filter((item) => item.id === event)[0];
      console.log(choosenItem);
      this.form.details[index].id = choosenItem.id;
      this.form.details[index].sensorNo = choosenItem.sensorNo;
      this.form.details[index].type = choosenItem.type;
      this.form.details[index].location = choosenItem.location;
    },
    getSensoroptions() {
      getSensorList().then(res => {
        this.Sensoroptions = res.data;
      });
    },
    addDetail() {
      this.form.details.push({ id: '', sensorName: '', sensorNo: '', type: '', location: "", alarmUpper: "", alarmLow: "" });
    },
    removeDetail(index) {
      if (index > 0) {
        this.form.details.splice(index, 1);
      } else {
        this.$message({
          message: "请至少添加一项主机",
          type: "warning",
        });
      }

    },

    // 查询数据
    getList() {
      this.loading = true;
      listHostMachine(this.queryParams).then(res => {
        if (res.code == 200) {
          this.dataList = res.data.result;
          this.total = res.data.totalNum;
          this.loading = false;
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelSet() {
      this.open2 = false;
      this.resetSet();
    },
    resetSet() {
      this.formSet = {
        ids: "",
        datePW: "",
        isPW: true
      };

      this.resetForm("formSet");
    },
    // 重置数据表单
    reset() {
      this.form = {
        id: undefined,
        machineName: undefined,
        machineNo: undefined,
        sort: undefined,
        location: undefined,
        machineSence: undefined,
        ip: undefined,
        status: undefined,
        wStatus: undefined,
        workMode: undefined,
        details: [{ id: '', sensorName: '', sensorNo: '', type: '', location: "", alarmUpper: "", alarmLow: "" }]
      };

      this.resetForm("form");
    },
    // 重置查询操作
    resetQuery() {
      this.timeRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1
      this.multiple = !selection.length;
    },
    // 自定义排序
    sortChange(column) {
      if (column.prop == null || column.order == null) {
        this.queryParams.sort = undefined;
        this.queryParams.sortType = undefined;
      } else {
        this.queryParams.sort = column.prop;
        this.queryParams.sortType = column.order;
      }

      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加喷雾主机";
      this.opertype = 1;
      console.log(this.typeOptions);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;

      this.$confirm('是否确认删除？')
        .then(function () {
          return delHostMachine(Ids);
        })
        .then(() => {
          this.handleQuery();
          this.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    handleSetHost(row) {
      if (row.id == undefined) {
        this.formSet.ids = this.ids.join(',');
      } else {
        this.formSet.ids = row.id;
      }

      this.open2 = true;
    },
    handleHostMachine() {
      this.open2 = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getHostMachine(id).then((res) => {
        const { code, data } = res;
        if (code == 200) {
          this.getSensoroptions();
          this.open = true;
          this.title = "修改喷雾主机数据";
          this.opertype = 2;

          this.form = {
            ...data,
          };

        }
      });
    },
    // 主机连接状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 水阀状态字典翻译
    wStatusFormat(row, column) {
      return this.selectDictLabel(this.wStatusOptions, row.wStatus);
    },
    submitSetForm: function () {

      this.$refs["formSet"].validate((valid) => {
        if (valid) {


          console.log(this.formSet)
          updateSetHostMachine(this.formSet)
            .then((res) => {
              this.msgSuccess("设置成功");
              this.open2 = false;
            })
            .catch((err) => {
              //TODO 错误逻辑
            });
        }
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(JSON.stringify(this.form));

          if (this.form.id != undefined && this.opertype === 2) {
            updateHostMachine(this.form)
              .then((res) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .catch((err) => {
                //TODO 错误逻辑
              });
          } else {
            addHostMachine(this.form)
              .then((res) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .catch((err) => {
                //TODO 错误逻辑
              });
          }
        }
      });
    },
  },
};
</script>